<?php

namespace App\Console\Commands;

use App\Models\InvoiceItems;
use App\Models\PayFee;
use Illuminate\Console\Command;
use Carbon\Carbon;
use App\Models\Report;
use App\Models\OrderRecord;

class InvoiceCount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:count';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发票统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $last_start_day = date("Y-m", strtotime("-3 months")) . "-".date("t")." 00:00:00";
        $last_end_day = date("Y-m" , strtotime("-2 months")) . "-" . (date("t", strtotime("-1 months"))-1)." 23:59:59";
        $last_start_time = strtotime($last_start_day);
        $last_end_time = strtotime($last_end_day);

        $start_day = date("Y-m", strtotime("-2 months")) . "-".(date("t", strtotime("-2 months")))." 00:00:00";
        $end_day = date("Y-m", strtotime("-1 months")) . "-" . (date("t")-1)." 23:59:59";
        $start_time = strtotime($start_day);
        $end_time = strtotime($end_day);

        $data = [];
        //当月收入总额
        $data[] = PayFee::where('pay_time','>=',$start_time)
            ->where('pay_time','<',$end_time)
            ->whereIn("pay_type",[2,3,4,5])
            ->sum("pay_amount");

        //当月收入中已开票额
        $data[] = InvoiceItems::where("send_time",">=",$start_time)
            ->where("send_time","<=",$end_time)
            ->where("bill_status","=",2)
            ->sum("total_price");


        //当月未开票金额
//        $data[] = OrderRecord::where("billing_date",">=",$start_time)
//            ->where("billing_date","<=",$end_time)
//            ->where("status","=",1)
//            ->where("invoice_order","=",'')
//            ->sum("parking_charge");
        $data[] = $data[0]-$data[1];
        //上月收入中当月开票
        $data[] = InvoiceItems::where("send_time",">=",$last_start_time)
            ->where("send_time","<=",$last_end_time)
            ->where("bill_status","=",2)
            ->sum("total_price");

        //存入数据库
        $report = new Report();
        $report->report_date = date("Y-m",$end_time);  //Carbon::yesterday()->format('Y-m-d');
        $report->type = 'invoice_count_month_report';
        $report->value = $data;
        $report->save();

        // 清除流量数据
        $this->info('收入统计成功');
    }

}
